home *** CD-ROM | disk | FTP | other *** search
/ Info-Mac 3 / Info_Mac_1994-01.iso / Development / Information / Mac Programming Secrets 1.0.1 / Chapter 03 / Standard Stuff.c < prev    next >
C/C++ Source or Header  |  1992-05-19  |  19KB  |  661 lines

  1. #include "Standard Stuff.h"
  2. #include "Traps.h"
  3.  
  4. /*******************************************************************************
  5.  
  6.     The “g” prefix is used to emphasize that a variable is global.
  7.  
  8. *******************************************************************************/
  9.  
  10. SysEnvRec    gMac;                /*    gMac is used to hold the result of a
  11.                                     SysEnvirons call. This makes it convenient
  12.                                     for any routine to check the environment. */
  13.  
  14. Boolean        gQuit;                /*    We set this to TRUE when the user selects
  15.                                     Quit from the File menu. Our main event
  16.                                     loop exists when gQuit is TRUE. */
  17.  
  18. Boolean        gInBackground;        /*    gInBackground is maintained by our osEvent
  19.                                     handling routines. Any part of the program
  20.                                     can check it to find out if it is currently
  21.                                     in the background. */
  22.  
  23.  
  24. /*******************************************************************************
  25.  
  26.     Define HiWrd and LoWrd macros for efficiency.
  27.  
  28. *******************************************************************************/
  29.  
  30. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  31. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  32.  
  33.  
  34. /*******************************************************************************
  35.  
  36.     main
  37.  
  38.     Entry point for our program. We initialize the toolbox, make sure we are
  39.     running on a sufficiently studly machine, and put up the menubar. Finally,
  40.     we start polling for events and handling them by entering our main event
  41.     loop.
  42.  
  43. *******************************************************************************/
  44. main()
  45. {
  46.     /*    If you have stack requirements that differ from the default,
  47.         then you could use SetApplLimit to increase StackSpace at
  48.         this point, before calling MaxApplZone. */
  49.  
  50.     MaxApplZone();                    /* Expand the heap so code segments load
  51.                                        at the top */
  52.     InitToolbox();                    /* Initialize the program */
  53.     MainEventLoop();                /* Call the main event loop */
  54. }
  55.  
  56.  
  57. /*******************************************************************************
  58.  
  59.     InitToolbox
  60.  
  61.     Set up the whole world, including global variables, Toolbox managers, and
  62.     menus.
  63.  
  64. *******************************************************************************/
  65. void InitToolbox()
  66. {
  67.     Handle        menuBar;
  68.     EventRecord event;
  69.     short        count;
  70.  
  71.     gInBackground = FALSE;
  72.     gQuit = FALSE;
  73.  
  74.     InitGraf((Ptr) &qd.thePort);
  75.     InitFonts();
  76.     InitWindows();
  77.     InitMenus();
  78.     TEInit();
  79.     InitDialogs(NIL);
  80.     InitCursor();
  81.  
  82.     /*    This next bit of code waits until MultiFinder brings our application
  83.         to the front. This gives us a better effect if we open a window at
  84.         startup. */
  85.  
  86.     for (count = 1; count <= 3; ++count)
  87.         EventAvail(everyEvent, &event);
  88.  
  89.     SysEnvirons(curSysEnvVers, &gMac);
  90.  
  91.     if (gMac.machineType < 0)
  92.         DeathAlert(errWimpyROMs);
  93.  
  94.     if (gMac.systemVersion < 0x0600)
  95.         DeathAlert(errWimpySystem);
  96.  
  97.     if (!TrapExists(_WaitNextEvent))
  98.         DeathAlert(errWeirdSystem);
  99.  
  100.     menuBar = GetNewMBar(rMenuBar);            /* Read menus into menu bar */
  101.     if ( menuBar == NIL )
  102.          DeathAlert(errNoMenuBar);
  103.     SetMenuBar(menuBar);                    /* Install menus */
  104.     DisposHandle(menuBar);
  105.     AddResMenu(GetMHandle(mApple), 'DRVR');    /* Add DA names to Apple menu */
  106.     AdjustMenus();
  107.     DrawMenuBar();
  108. }
  109.  
  110.  
  111. /*******************************************************************************
  112.  
  113.     MainEventLoop
  114.  
  115.     Get events forever, and handle them by calling HandleEvent. First, call
  116.     DoAdjustCursor to set our cursor shape, and to set the cursor region. We
  117.     then call WaitNextEvent() to get the event. This is OK, because we know
  118.     we’re running on System 6.0 or later by this time. If we got an event, we
  119.     handle it by calling HandleEvent(). But before doing that, we call
  120.     DoAdjustCursor again in case our application had fallen asleep under
  121.     MultiFinder.
  122.  
  123. *******************************************************************************/
  124. void MainEventLoop()
  125. {
  126.     RgnHandle    cursorRgn;
  127.     Boolean        gotEvent;
  128.     EventRecord    event;
  129.     Point        mouse;
  130.  
  131.     cursorRgn = NIL;
  132.     while ( !gQuit ) {
  133.         gotEvent = WaitNextEvent(everyEvent, &event, MAXLONG, cursorRgn);
  134.         if ( gotEvent ) {
  135.             HandleEvent(&event);
  136.         }
  137.     }
  138. }
  139.  
  140.  
  141. /*******************************************************************************
  142.  
  143.     HandleEvent
  144.  
  145.     Do the right thing for an event. Determine what kind of event it is, and
  146.     call the appropriate routines.
  147.  
  148. *******************************************************************************/
  149. void HandleEvent(EventRecord *event)
  150. {
  151.     switch ( event->what ) {
  152.         case mouseDown:
  153.             HandleMouseDown(event);
  154.             break;
  155.         case keyDown:
  156.         case autoKey:
  157.             HandleKeyPress(event);
  158.             break;
  159.         case activateEvt:
  160.             HandleActivate(event);
  161.             break;
  162.         case updateEvt:
  163.             HandleUpdate(event);
  164.             break;
  165.         case diskEvt:
  166.             HandleDiskInsert(event);
  167.             break;
  168.         case osEvt:
  169.             HandleOSEvent(event);
  170.             break;
  171.     }
  172. }
  173.  
  174.  
  175. /*******************************************************************************
  176.  
  177.     HandleActivate
  178.  
  179.     This is called when a window is activated or deactivated. In this sample,
  180.     the Window Manager’s handling of activate and deactivate events is
  181.     sufficient. Other applications may have TextEdit records, controls, lists,
  182.     etc., to activate/deactivate.
  183.  
  184. *******************************************************************************/
  185. void HandleActivate(EventRecord *event)
  186. {
  187.     WindowPtr    theWindow;
  188.     Boolean        becomingActive;
  189.  
  190.     theWindow = (WindowPtr) event->message;
  191.     becomingActive = (event->modifiers & activeFlag) != 0;
  192.     if ( IsAppWindow(theWindow) ) {
  193.         DrawGrowIcon(theWindow);
  194.         /* DoActivateWindow(theWindow, becomingActive) */;
  195.     }
  196. }
  197.  
  198.  
  199. /*******************************************************************************
  200.  
  201.     HandleDiskInsert
  202.  
  203.     Called when we get a disk inserted event. Check the upper word of the
  204.     event message; if it’s non-zero, then a bad disk was inserted, and it
  205.     needs to be formatted.
  206.  
  207. *******************************************************************************/
  208. void HandleDiskInsert(EventRecord *event)
  209. {
  210.     Point    aPoint = {100, 100};
  211.  
  212.     if ( HiWrd(event->message) != noErr ) {
  213.         (void) DIBadMount(aPoint, event->message);
  214.     }
  215. }
  216.  
  217.  
  218. /*******************************************************************************
  219.  
  220.     HandleKeyPress
  221.  
  222.     The user pressed a key. What are you going to do about it?
  223.  
  224. *******************************************************************************/
  225. void HandleKeyPress(EventRecord *event)
  226. {
  227.     char    key;
  228.  
  229.     key = event->message & charCodeMask;
  230.     if ( event->modifiers & cmdKey ) {        /* Command key down? */
  231.         AdjustMenus();                        /* Enable/disable/check menu items properly */
  232.         HandleMenuCommand(MenuKey(key));
  233.     } else {
  234.         /* DoKeyPress(event) */;
  235.     }
  236. }
  237.  
  238.  
  239. /*******************************************************************************
  240.  
  241.     HandleMouseDown
  242.  
  243.     Called to handle mouse clicks. The user could have clicked anywhere, so
  244.     let’s first find out where by calling FindWindow. That returns a number
  245.     indicating where in the screen the mouse was clicked. “switch” on that
  246.     number and call the appropriate routine.
  247.  
  248. *******************************************************************************/
  249. void HandleMouseDown(EventRecord *event)
  250. {
  251.     long        newSize;
  252.     Rect        growRect;
  253.     WindowPtr    theWindow;
  254.     short        part = FindWindow(event->where, &theWindow);
  255.  
  256.     switch ( part ) {
  257.         case inMenuBar:                /* Process a mouse menu command (if any) */
  258.             AdjustMenus();
  259.             HandleMenuCommand(MenuSelect(event->where));
  260.             break;
  261.         case inSysWindow:            /* Let the system handle the mouseDown */
  262.             SystemClick(event, theWindow);
  263.             break;
  264.         case inContent:
  265.             if ( theWindow != FrontWindow() )
  266.                 SelectWindow(theWindow);
  267.             else
  268.                 /* DoContentClick(event, theWindow) */;
  269.             break;
  270.         case inDrag:                /* Pass screenBits.bounds to get all gDevices */
  271.             DragWindow(theWindow, event->where, &qd.screenBits.bounds);
  272.             break;
  273.         case inGrow:
  274.             growRect = qd.screenBits.bounds;
  275.             growRect.top = growRect.left = 80;        /* Arbitrary minimum size. */
  276.             newSize = GrowWindow(theWindow, event->where, &growRect);
  277.             if (newSize != 0) {
  278.                 InvalidateScrollbars(theWindow);
  279.                 SizeWindow(theWindow, LoWrd(newSize), HiWrd(newSize), TRUE);
  280.                 InvalidateScrollbars(theWindow);
  281.             }
  282.             break;
  283.         case inGoAway:
  284.             if (TrackGoAway(theWindow, event->where))  {
  285.                 CloseAnyWindow(theWindow);
  286.             }
  287.             break;
  288.         case inZoomIn:
  289.         case inZoomOut:
  290.             if (TrackBox(theWindow, event->where, part)) {
  291.                 SetPort(theWindow);
  292.                 EraseRect(&theWindow->portRect);
  293.                 ZoomWindow(theWindow, part, TRUE);
  294.                 InvalRect(&theWindow->portRect);
  295.             }
  296.             break;
  297.     }
  298. }
  299.  
  300.  
  301. /*******************************************************************************
  302.  
  303.     HandleOSEvent
  304.  
  305.     Deal with OSEvents (formerly, app4Events). These are message that
  306.     MultiFinder -- known as the Process Manager under System 7.0 -- sends to
  307.     us. Here, we deal with suspend and resume message.
  308.  
  309. *******************************************************************************/
  310. void HandleOSEvent(EventRecord *event)
  311. {
  312.     switch ((event->message >> 24) & 0x00FF) {        /* High byte of message */
  313.         case suspendResumeMessage:
  314.  
  315.             /*    In our SIZE resource, we say that we are MultiFinder aware.
  316.                 This means that we take on the responsibility of activating
  317.                 and deactivating our own windows on suspend/resume events. */
  318.  
  319.             gInBackground = (event->message & resumeFlag) == 0;
  320.             if (FrontWindow()) {
  321.                 DrawGrowIcon(FrontWindow());
  322.                 /* DoActivateWindow(FrontWindow(), !gInBackground); */
  323.             }
  324.             break;
  325.         case mouseMovedMessage:
  326.             break;
  327.     }
  328. }
  329.  
  330.  
  331. /*******************************************************************************
  332.  
  333.     HandleUpdate
  334.  
  335.     This is called when an update event is received for a window. It calls
  336.     DoUpdateWindow to draw the contents of an application window. As an
  337.     efficiency measure that does not have to be followed, it calls the drawing
  338.     routine only if the visRgn is non-empty. This will handle situations where
  339.     calculations for drawing or drawing itself is very time-consuming.
  340.  
  341. *******************************************************************************/
  342. void HandleUpdate(EventRecord *event)
  343. {
  344.     WindowPtr    theWindow = (WindowPtr) event->message;
  345.     if ( IsAppWindow(theWindow) ) {
  346.         BeginUpdate(theWindow);                /* This sets up the visRgn */
  347.         if (!EmptyRgn(theWindow->visRgn)) {    /* Draw if updating needs to be done */
  348.             SetPort(theWindow);
  349.             EraseRgn(theWindow->visRgn);
  350.             /* DoUpdateWindow(event) */;
  351.             DrawGrowIcon(theWindow);
  352.         }
  353.         EndUpdate(theWindow);
  354.     }
  355. }
  356.  
  357.  
  358. /*******************************************************************************
  359.  
  360.     AdjustMenus
  361.  
  362.     Enable and disable menus based on the current state. The user can only
  363.     select enabled menu items. We set up all the menu items before calling
  364.     MenuSelect or MenuKey, since these are the only times that a menu item can
  365.     be selected. Note that MenuSelect is also the only time the user will see
  366.     menu items. This approach to deciding what enable/disable state a menu
  367.     item has the advantage of concentrating all the decision-making in one
  368.     routine, as opposed to being spread throughout the application. Other
  369.     application designs may take a different approach that is just as valid.
  370.  
  371. *******************************************************************************/
  372. void AdjustMenus()
  373. {
  374.     WindowPtr    window;
  375.     MenuHandle    menu;
  376.  
  377.     window = FrontWindow();
  378.  
  379.     menu = GetMHandle(mFile);
  380.     if ( window != NIL )
  381.         EnableItem(menu, iClose);
  382.     else
  383.         DisableItem(menu, iClose);
  384.  
  385.     menu = GetMHandle(mEdit);
  386.     if ( IsDAWindow(window) ) {        /* A desk accessory might need the edit menu… */
  387.         EnableItem(menu, iUndo);
  388.         EnableItem(menu, iCut);
  389.         EnableItem(menu, iCopy);
  390.         EnableItem(menu, iClear);
  391.         EnableItem(menu, iPaste);
  392.     } else {                        /* … but we don’t use it. */
  393.         DisableItem(menu, iUndo);
  394.         DisableItem(menu, iCut);
  395.         DisableItem(menu, iCopy);
  396.         DisableItem(menu, iClear);
  397.         DisableItem(menu, iPaste);
  398.     }
  399. }
  400.  
  401.  
  402. /*******************************************************************************
  403.  
  404.     HandleMenuCommand
  405.  
  406.     This is called when an item is chosen from the menu bar (after calling
  407.     MenuSelect or MenuKey). It performs the right operation for each command.
  408.     It is good to have both the result of MenuSelect and MenuKey go to one
  409.     routine like this to keep everything organized.
  410.  
  411. *******************************************************************************/
  412. void HandleMenuCommand(menuResult)
  413.     long        menuResult;
  414. {
  415.     short        menuID;                /* The resource ID of the selected menu */
  416.     short        menuItem;            /* The item number of the selected menu */
  417.     Str255        daName;
  418.  
  419.     menuID = HiWrd(menuResult);
  420.     menuItem = LoWrd(menuResult);
  421.     switch ( menuID ) {
  422.         case mApple:
  423.             switch ( menuItem ) {
  424.                 case iAbout:
  425.                     (void) Alert(rAboutAlert, NIL);
  426.                     break;
  427.                 default:            /* All non-About items in this menu are DAs */
  428.                     GetItem(GetMHandle(mApple), menuItem, daName);
  429.                     (void) OpenDeskAcc(daName);
  430.                     break;
  431.             }
  432.             break;
  433.         case mFile:
  434.             switch ( menuItem ) {
  435.                 case iNew:
  436.                     /* DoNewWindow(); */
  437.                     break;
  438.                 case iClose:
  439.                     CloseAnyWindow(FrontWindow());
  440.                     break;
  441.                 case iQuit:
  442.                     gQuit = TRUE;
  443.                     break;
  444.             }
  445.             break;
  446.         case mEdit:
  447.             switch (menuItem) {
  448.                 /* Call SystemEdit for DA editing & MultiFinder */
  449.                 /* since we don’t do any Editing */
  450.                 case iUndo:
  451.                 case iCut:
  452.                 case iCopy:
  453.                 case iPaste:
  454.                 case iClear:
  455.                     (void) SystemEdit(menuItem-1);
  456.                     break;
  457.             }
  458.             break;
  459.     }
  460.     HiliteMenu(0);        /* Unhighlight what MenuSelect or MenuKey hilited */
  461. }
  462.  
  463.  
  464. /*******************************************************************************
  465.  
  466.     CloseAnyWindow
  467.  
  468.     Close the given window in a manner appropriate for that window. If the
  469.     window belongs to a DA, we call CloseDeskAcc. For dialogs, we simply hide
  470.     the window. If we had any document windows, we would probably call either
  471.     DisposeWindow or CloseWindow after disposing of any document data and/or
  472.     controls.
  473.  
  474. *******************************************************************************/
  475. void CloseAnyWindow(WindowPtr window)
  476. {
  477.     if (IsDAWindow(window)) {
  478.         CloseDeskAcc( ( (WindowPeek) window )->windowKind );
  479.     } else if (IsDialogWindow(window)) {
  480.         HideWindow(window);
  481.     } else if (IsAppWindow(window)) {
  482.         /* Do something significant for document windows. */
  483.     }
  484. }
  485.  
  486.  
  487. /*******************************************************************************
  488.  
  489.     DeathAlert
  490.  
  491.     Display an alert that tells the user an error occurred, then exit the
  492.     program. This routine is used as an ultimate bail-out for serious errors
  493.     that prohibit the continuation of the application. The error number is
  494.     used to index an 'STR#' resource so that a relevant message can be
  495.     displayed.
  496.  
  497. *******************************************************************************/
  498. void DeathAlert(short errNumber)
  499. {
  500.     short        itemHit;
  501.     Str255        theMessage;
  502.  
  503.     SetCursor(&qd.arrow);
  504.     GetIndString(theMessage, rErrorStrings, errNumber);
  505.     ParamText(theMessage, NIL, NIL, NIL);
  506.     itemHit = StopAlert(rErrorAlert, NIL);
  507.     ExitToShell();
  508. }
  509.  
  510.  
  511. /*******************************************************************************
  512.  
  513.     IsAppWindow
  514.  
  515.     Check to see if a window belongs to the application. If the window pointer
  516.     passed was NIL, then it could not be an application window. WindowKinds
  517.     that are negative belong to the system and windowKinds less than userKind
  518.     are reserved by Apple except for windowKinds equal to dialogKind, which
  519.     mean it is a dialog.
  520.  
  521. *******************************************************************************/
  522. Boolean IsAppWindow(WindowPtr window)
  523. {
  524.     short        windowKind;
  525.  
  526.     if ( window == NIL )
  527.         return false;
  528.     else {
  529.         windowKind = ((WindowPeek) window)->windowKind;
  530.         return ((windowKind >= userKind) || (windowKind == dialogKind));
  531.     }
  532. }
  533.  
  534.  
  535. /*******************************************************************************
  536.  
  537.     IsDAWindow
  538.  
  539.     Check to see if a window belongs to a desk accessory. It belongs to a DA
  540.     if the windowKind field of the window record is negative.
  541.  
  542. *******************************************************************************/
  543. Boolean IsDAWindow(WindowPtr window)
  544. {
  545.     if ( window == NIL )
  546.         return false;
  547.     else
  548.         return ( ((WindowPeek) window)->windowKind < 0 );
  549. }
  550.  
  551.  
  552. /*******************************************************************************
  553.  
  554.     IsDialogWindow
  555.  
  556.     Check to see if a window is a dialog window. We can determine this be
  557.     checking to see if the windowKind field is equal to dialogKind.
  558.  
  559. *******************************************************************************/
  560. Boolean IsDialogWindow(WindowPtr window)
  561. {
  562.     if ( window == NIL )
  563.         return false;
  564.     else
  565.         return ( ((WindowPeek) window)->windowKind == dialogKind );
  566. }
  567.  
  568.  
  569. /*******************************************************************************
  570.  
  571.     InvalidateScrollbars
  572.  
  573.     Call InvalRect on the right and bottom edges of a window. This routine is
  574.     called during the resizing of a window to take care of the scrollbar lines
  575.     and grow icon.
  576.  
  577. *******************************************************************************/
  578. void InvalidateScrollbars(WindowPtr theWindow)
  579. {
  580.     Rect    tempRect;
  581.  
  582.     SetPort(theWindow);
  583.  
  584.     tempRect = theWindow->portRect;
  585.     tempRect.left = tempRect.right - 15;
  586.     InvalRect(&tempRect);
  587.     EraseRect(&tempRect);
  588.  
  589.     tempRect = theWindow->portRect;
  590.     tempRect.top = tempRect.bottom - 15;
  591.     InvalRect(&tempRect);
  592.     EraseRect(&tempRect);
  593. }
  594.  
  595.  
  596. /*******************************************************************************
  597.  
  598.     TrapExists
  599.  
  600.     Check to see if a given trap is implemented. The recommended approach to
  601.     see if a trap is implemented is to see if the address of the trap routine
  602.     is the same as the address of the _Unimplemented trap. However, we must
  603.     also make sure that the trap is contained in the trap table on the machine
  604.     we’re running on. Not all Macintoshes have the same sized trap tables. We
  605.     call NumToolboxTraps to find out the size of the table. If the trap we are
  606.     examining falls off the end, then we treat it as automatically being
  607.     unimplemented.
  608.  
  609. *******************************************************************************/
  610. Boolean    TrapExists(short theTrap)
  611. {
  612.     TrapType    theTrapType;
  613.  
  614.     theTrapType = GetTrapType(theTrap);
  615.     if ((theTrapType == ToolTrap) && ((theTrap &= 0x07FF) >= NumToolboxTraps()))
  616.         return false;
  617.     else
  618.         return (NGetTrapAddress(_Unimplemented, ToolTrap) !=
  619.                 NGetTrapAddress(theTrap, theTrapType));
  620. }
  621.  
  622.  
  623. /*******************************************************************************
  624.  
  625.     GetTrapType
  626.  
  627.     Check the bits of a trap number to determine its type. If bit 11 is set,
  628.     it’s a toolbox trap. Otherwise, it’s an OS trap.
  629.  
  630. *******************************************************************************/
  631. TrapType    GetTrapType(short theTrap)
  632. {
  633.     if ((theTrap & 0x0800) == 0)                    /* Per D.A. */
  634.         return (OSTrap);
  635.     else
  636.         return (ToolTrap);
  637. }
  638.  
  639.  
  640. /*******************************************************************************
  641.  
  642.     NumToolboxTraps
  643.  
  644.     Find the size of the Toolbox trap table. This can be either 0x0200 or
  645.     0x0400 bytes, depending on which Macintosh we are running on. We determine
  646.     the size by taking advantage of an anomaly of the smaller trap table: any
  647.     entries that fall beyond the end of the table are mirrored back down into
  648.     the lower part. For example, on a large table, trap numbers A86E and AA6E
  649.     correspond to different routines. However, on a small table, they
  650.     correspond to the same routine. By checking the addresses of these
  651.     routines, we can determine the size of the table.
  652.  
  653. *******************************************************************************/
  654. short    NumToolboxTraps(void)
  655. {
  656.     if (NGetTrapAddress(0xA86E, ToolTrap) == NGetTrapAddress(0xAA6E, ToolTrap))
  657.         return (0x200);
  658.     else
  659.         return (0x400);
  660. }
  661.